package com.library.librarybackend.config;

import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.library.librarybackend.domain.ResponseStatus;
import com.library.librarybackend.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 平
 * @description web配置
 * @since 2025-09-20 19:21
 */
@Slf4j
@Configuration
public class WebFilter {


    private static final String[] EXCLUDE_PATH_PATTERNS = {
            // Swagger
            "**/swagger-ui.html",
            "/swagger-resources/**",
            "/webjars/**",
            "/v2/**",
            "/v3/**",
            "/swagger-ui.html/**",
            "/swagger-ui/**",
            "/doc.html/**",
            "/error",
            "/favicon.ico",
            "/csrf",
            "/auth/login",
            "/auth/register",
    };

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }


    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                // 指定 拦截路由 与 放行路由
                .addInclude("/**")
                .addExclude(EXCLUDE_PATH_PATTERNS)
                .setAuth(obj -> StpUtil.checkLogin())
                .setError(e -> {
                    log.error("认证异常:", e);
                    return JSONUtil.parse(Result.from(ResponseStatus.UNAUTHORIZED));
                });
    }


}
